//
//  PenInfoViewController.swift
//  SmartPenSwift
//
//  Created by tql on 2021/3/3.
//

import UIKit
import SmartPenSDK
import SVProgressHUD

class PenInfoViewController: UIViewController {

    var currentSelectShoutDownTime : Int = 0
    var penBeepResult : Int = 0
    
    lazy var tableView : UITableView = {
        let table = UITableView.init(frame: self.view.bounds, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.backgroundColor = .clear
        table.register(PenInfo_OneTabCell.classForCoder(), forCellReuseIdentifier: "PenInfo_OneTabCell")
        table.register(PenInfo_TwoTabCell.classForCoder(), forCellReuseIdentifier: "PenInfo_TwoTabCell")
        table.register(PenInfo_ThreeTabCell.classForCoder(), forCellReuseIdentifier: "PenInfo_ThreeTabCell")
        table.register(PenInfo_FourTabCell.classForCoder(), forCellReuseIdentifier: "PenInfo_FourTabCell")
        table.register(PenInfo_FiveTabCell.classForCoder(), forCellReuseIdentifier: "PenInfo_FiveTabCell")

        table.layer.cornerRadius = 10
        table.layer.shadowColor = UIColor.lightGray.cgColor
        table.layer.shadowOffset = CGSize(width: 2, height: 2)
        table.layer.shadowOpacity = 0.2
        
        table.showsVerticalScrollIndicator = false
        table.separatorStyle = .none
        table.estimatedRowHeight = 100
        
        return table
    }()
    
    lazy var penCommAgent : PenCommAgent = PenCommAgent.getInstance()
    lazy var titleArray : [[String]] = [["笔名","蓝牙地址","蓝牙固件版本","MCU固件版本"],
                                        ["客户ID","剩余电量","已用内存","RTC时间"],
                                        ["蜂鸣器","笔尖压力唤醒","呼吸灯","自动关机时间"],
                                        ["灵敏度","压力值范围","点读码值"],
                                        ["保存日志","笔锋绘制","过滤算法"]
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor(hex: "F3F3F3")
        penCommAgent.pensignal = self
        penCommAgent.reqPenStatus()
        navigationItem.title = "笔参数"
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(self.view).inset(10)
            make.left.right.equalTo(self.view)
        }

        
    }
    
 

}
extension PenInfoViewController : TQLPenSignal{
    
    func onDisconnected() {
        self.navigationController?.popViewController(animated: true)
    }
    func onPenAutoPower(onSetUpResponse isSuccess: Bool) {
        if isSuccess {
            penCommAgent.reqPenAutoOnMode()
        }
        debugPrint("自动开机模式" + ((isSuccess == true) ? "成功" : "失败"))
        
    }
    
    func onRecievePenElementCode(_ ElementCode: ElementCode!) {
        
    }
    func onRecieveMacAdress(_ MacAdress: String!) {
        debugPrint("MacAdress =  \(MacAdress!)")
    }
    
    func onReceivePenStatus(_ timetick: String!, penName: String!, macAdress: String!, forcemax: Int32, battery: Int32, usedmem: Int32, autopowerMode: Bool, beep: Bool, autoshutdownTime: Int16, penSensitivity: Int16, penColor: Int32, comstomerID ComstomerID: String!, penModel: String!, offlineDataList dataList: Int32) {
        debugPrint(#function)
        self.tableView.reloadData()
    }
}


extension PenInfoViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        debugPrint(#function)
    }
}
extension PenInfoViewController : UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 5//
//        let secArray : [String] = titleArray[section]
//        debugPrint("secArray === \(secArray)" + "section = \(section)")
//        return secArray.count
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          
        if indexPath.row==0 {
            let cell : PenInfo_OneTabCell = tableView.dequeueReusableCell(withIdentifier: "PenInfo_OneTabCell", for: indexPath) as! PenInfo_OneTabCell
            cell.penNameLabel.text = penCommAgent.getPenName()
            cell.macAddressLabel.text = penCommAgent.getPenMac()
            cell.bleVersionLabel.text = penCommAgent.getPenFirmWare()
            cell.mcuVersionLabel.text = penCommAgent.getMcuFirmwareVersion()
            cell.btnclickBlock = { [weak self] tagIndex  in
                debugPrint("tagindex = \(tagIndex)")
                self?.actionWith(btnTag: tagIndex, Row: indexPath.row)
            }
            return cell
        }else if indexPath.row == 1{
            
            let cell : PenInfo_TwoTabCell = tableView.dequeueReusableCell(withIdentifier: "PenInfo_TwoTabCell", for: indexPath) as! PenInfo_TwoTabCell

            cell.customeIDLabel.text = penCommAgent.getCurrentPenModel()
            cell.remainPowerLabel.text = "\(penCommAgent.getBattery())"
            cell.useMemoryLabel.text = "\(penCommAgent.getUsedmem())"+"%"
            cell.RCTTimeLabel.text = penCommAgent.getRTCTime()
            cell.btnclickBlock = { [weak self] tagIndex in
                self?.actionWith(btnTag: tagIndex, Row: indexPath.row)
            }
            
            return cell
            
        }else if indexPath.row == 2{
            
            let cell : PenInfo_ThreeTabCell = tableView.dequeueReusableCell(withIdentifier: "PenInfo_ThreeTabCell", for: indexPath) as! PenInfo_ThreeTabCell

            cell.ledonSwitch.isOn = penCommAgent.getLEDConfig()
            cell.beepSwitch.isOn = (penCommAgent.getBeep() == true) ? true : false
            
            if penCommAgent.getCurrentPenModel() == "YX-201" {
                cell.beepSwitch.isOn = false
                cell.beepSwitch.isEnabled = false
                cell.ledonSwitch.isEnabled = false
                cell.ledonSwitch.isOn = false
            }else if penBeepResult == 2 {
                cell.beepSwitch.isOn = false
                cell.beepSwitch.isEnabled = false
            }else if penCommAgent.getCurrentPenModel() == "TQL-130" {
                cell.ledonSwitch.isOn = false
                cell.ledonSwitch.isEnabled = false
            }
            
            cell.PressPowerSwitch .isOn = penCommAgent.getAutopowermode()
            cell.autoPowerTimeLabel.text = "\(penCommAgent.getAutoShutDownTime())"
            cell.btnclickBlock  = { [weak self] tagIndex in
                self?.actionWith(btnTag: tagIndex, Row: indexPath.row)
            }
            cell.SwitchStateChangeBlock = {[weak self] changState , UIIndex in
                self?.SwitchActionWith(changState, UIIndex, indexPath.row)
            }
            
            return cell
            
        }else if indexPath.row == 3{
            
            let cell : PenInfo_FourTabCell = tableView.dequeueReusableCell(withIdentifier: "PenInfo_FourTabCell", for: indexPath) as! PenInfo_FourTabCell

            cell.sensitiveLabel.text = "\(penCommAgent.getPenSensitivity())"
            cell.pressRangeLable.text = penCommAgent.getSensitivityCorrection() ?? ""
            cell.elementCodeValueLabel.text = "\(penCommAgent.getElementCode()?.index ?? 0)"
            cell.btnclickBlock = { [weak self] btntag in
                self?.actionWith(btnTag: btntag, Row: indexPath.row)
            }
            
            return cell
            
        }else{
            let cell : PenInfo_FiveTabCell = tableView.dequeueReusableCell(withIdentifier: "PenInfo_FiveTabCell", for: indexPath) as! PenInfo_FiveTabCell

            cell.saveLogSwitch.isOn = UserDefaults.standard.bool(forKey: kAutoSaveLog)
            cell.penStrokeSwitch.isOn = UserDefaults.standard.bool(forKey: kStrokePen)
            cell.needFilterSwitch.isOn = UserDefaults.standard.bool(forKey: kNeedFilter)
            cell.SwitchStateChangeBlock = { [weak self] changeState, UIIndex in
                self?.SwitchActionWith(changeState, UIIndex, indexPath.row)
            }
            return cell
            
        }
        
        
    }
    
    func actionWith(btnTag btntag : Int, Row row : Int) -> Void {
        debugPrint(#function)
        if btntag == 0 && row == 0 {
            showChangePenNameViewAlert()
        }else if btntag == 3 && row == 1 {
            penCommAgent.writePenTime()
            SVProgressHUD.showInfo(withStatus: "RCT时间已经发送成功")
        }else if btntag == 0 && row == 3 {
            showSensitiveSettingView()
        }else if btntag == 3 && row == 2 {
            showAlertChangeShutDownTime()
        }
        
    }
    func SwitchActionWith(_ changeState : Bool, _ UIIndex : Int, _ row : Int) -> Void {
        debugPrint(#function)

        if UIIndex == 1 && row == 2 {
            penCommAgent.writePenBeep(changeState)
        }else if UIIndex == 2 && row == 2 {
            penCommAgent.writePenAuto(onMode: changeState)
        }else if UIIndex == 3 && row == 2 {
            penCommAgent.writeLEDConfig(changeState)
        }else if UIIndex == 1 && row == 4 {
            UserDefaults.standard.setValue(changeState, forKey: kAutoSaveLog)
            NotificationCenter.default.post(name: NSNotification.Name("kNotification_AutoSaveLog"), object: changeState)
        }else if UIIndex == 2 && row == 4 {
            UserDefaults.standard.setValue(changeState, forKey: kStrokePen)
            NotificationCenter.default.post(name: NSNotification.Name("kNotification_StrokePen"), object: changeState)
        }else if UIIndex == 3 && row == 4 {
            UserDefaults.standard.setValue(changeState, forKey: kNeedFilter)
            NotificationCenter.default.post(name: NSNotification.Name("kNotification_NeedFilter"), object: changeState)
        }
    }
    
    
}

extension PenInfoViewController{
    func showChangePenNameViewAlert() -> Void {
        debugPrint(#function)
        let alert : UIAlertController = UIAlertController.init(title: "设置笔名", message: "", preferredStyle: .alert)
        
        alert.addTextField { [weak self] (textField) in
            textField.placeholder = "长度保证在>3且<10"
            textField.text =  self?.penCommAgent.getPenName() ?? ""
        }
        
        let connectAction : UIAlertAction = UIAlertAction.init(title: "确认", style: .default) {[weak self] (action) in
            
            let tef : UITextField = alert.textFields?.first as! UITextField
         
            if tef.text?.count ?? 0 > 3 && tef.text?.count ?? 0 <= 10 {
                self?.penCommAgent.writePenName(tef.text!)
            }else{
            
                SVProgressHUD.showError(withStatus: "长度不规范，>3且<10")
            }
         
            
            
            
        }
        connectAction.setValue(UIColor(hex: "FF4E4E"), forKey: "_titleTextColor")
        alert.addAction(connectAction)
        
        let cancelAction : UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        cancelAction.setValue(UIColor(hex: "8492A6"), forKey: "_titleTextColor")
        alert.addAction(cancelAction)
        
        let cell : PenInfo_ThreeTabCell = self.tableView.cellForRow(at: NSIndexPath.init(row: 2, section: 0) as IndexPath) as! PenInfo_ThreeTabCell
        alert.popoverPresentationController?.sourceView = cell.autoPowerTimeLabel
        alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 10, height: 10)
        
        
        self.present(alert, animated: true, completion: nil)
    }
    func showSensitiveSettingView() -> Void {
        let view : SensitiveSettingView = SensitiveSettingView.init(frame: self.view.frame)
        view.currentIndex = Int( penCommAgent.getPenSensitivity())
        view.show()
        
        view.changeIndexBLock = {[weak self] changeIndex  in
            self?.penCommAgent.writePenSensitivity(Int32( changeIndex))
        }
        
    }
    func showAlertChangeShutDownTime() -> Void {
        debugPrint(#function)
        let alert : UIAlertController = UIAlertController.init(title: "设置笔自动关机时间", message: "时长未操作自动关机", preferredStyle: .alert)
        
        alert.addTextField { (textField) in
            textField.placeholder = "0表示不关机,1~20分钟之间选择"
            textField.keyboardType = .numberPad;
            textField.leftViewMode = .always
            textField.leftView = {
                let view = UIView.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
                return view
            }()
            
            textField.rightViewMode = .always
            textField.rightView = {
                let view = UIView.init(frame: CGRect(x: 0, y: 0, width: 30, height: 20))
                let lab : UILabel  = UILabel.init(frame: view.frame)
                view.addSubview(lab)
                lab.text = "min"
                lab.textColor = UIColor(hex: "151515")
                lab.font = UIFont.systemFont(ofSize: 12)
                return view
            }()
            
            textField.layer.borderColor =  UIColor(hex: "EC6938").cgColor
            
        }
        
        let connectAction : UIAlertAction = UIAlertAction.init(title: "确认", style: .default) {[weak self] (action) in
            
            let tef : UITextField = alert.textFields?.first as! UITextField
            
            let setToRemove : NSCharacterSet = NSCharacterSet.init(charactersIn: "0123456789").inverted as! NSCharacterSet;
            
            var resultstring : String = tef.text?.components(separatedBy: setToRemove as CharacterSet).joined(separator: "") ?? "0"
            var result : Int = Int(resultstring) ?? 0
            if result < 0{
                result = 0
            }else if result > 20{
                result = 20
            }
            
            self?.penCommAgent.writePenAuto(onMode: (result != 0))
            SVProgressHUD.showInfo(withStatus: "自动关机时间已发送")
            
            
        }
        connectAction.setValue(UIColor(hex: "FF4E4E"), forKey: "_titleTextColor")
        alert.addAction(connectAction)
        
        let cancelAction : UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        cancelAction.setValue(UIColor(hex: "8492A6"), forKey: "_titleTextColor")
        alert.addAction(cancelAction)
        
        let cell : PenInfo_ThreeTabCell = self.tableView.cellForRow(at: NSIndexPath.init(row: 2, section: 0) as IndexPath) as! PenInfo_ThreeTabCell
        alert.popoverPresentationController?.sourceView = cell.autoPowerTimeLabel
        alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 10, height: 10)
        
        
        self.present(alert, animated: true, completion: nil)
    }
}
